package com.woniuxy.service.impl;

import com.woniuxy.dao.RegistDao;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.entity.User;
import com.woniuxy.service.RegistService;
import com.woniuxy.utils.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @Author 罗蔚
 * @Date 2022/4/5 17:36
 * @Description TODO
 */
@Service
public class RegistServiceImpl implements RegistService {
    @Autowired
    RegistDao registDao;

    @Override
    public ResponseEntity existUsername(String username) {
        User user = registDao.findByUsername(username);
        if (user == null) {
            return ResponseEntity.SUCCESSFUL;
        }else {
            return ResponseEntity.FAIL;
        }
    }

    @Override
    public ResponseEntity addUser(User user) {
        // 随机生成一个激活码
        String code = UUID.randomUUID().toString().replace("-", "");
        user.setCode(code);

        int i = registDao.addUser(user);
        // 发送邮件
        String context = "<a href='http://localhost:8080/registConreoller/active?code=" + code + "'>点击该链接进行激活</a>";
        MailUtils.sendMail(user.getEmail(), context, "测试邮件");
        if (i != 0) {
            return ResponseEntity.SUCCESSFUL;
        }else {
            return ResponseEntity.FAIL;
        }
    }

    @Override
    public ResponseEntity active(String code) {
        User user = registDao.findUserByCode(code);

        if (user != null) {
            //查到了, 就修改status
            registDao.updateStatus(user);
            //激活成功
            return ResponseEntity.SUCCESSFUL;
        } else {
            return ResponseEntity.FAIL;
        }
    }
}
